package main.java.ejb.user;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import main.java.enity.Group;
import main.java.enity.User;

/**
 * Session Bean implementation class UserBean
 */
@Stateless(mappedName = "user")
public class UserBean implements UserEJB {

	@PersistenceContext(unitName = "Project3Final")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public UserBean() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public User logIn(String username, String password) {
		// TODO Auto-generated method stub
		try {
			User user = em.find(User.class, username);
			if (user != null) {
				if (password.equals(user.getPassword())) {
					return user;
				}
			}
		} catch (Exception ex) {
			return null;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see main.java.ejb.user.UserEJB#AddUser(java.lang.String,
	 * java.lang.String, java.lang.String, int)
	 */
	@Override
	public String AddUser(String Username, String Password, String email,
			int Groupid) {
		try {
			if (em.find(User.class, Username) == null) {
				Group group = em.find(Group.class, Groupid);

				if (group != null) {
					User user = new User();

					user.setEmail(email);
					user.setUsername(Username);
					user.setPassword(Password);
					user.setGroup(group);

					em.persist(user);

					em.flush();

					return user.getUsername();
				}
			}
		} catch (Exception ex) {
			return "";
		}
		return "";
	}

}
